package com.printeverywhere.servlet;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import antlr.collections.Enumerator;

import com.printeverywhere.util.CommonUtil;

public class FileUploadServlet extends HttpServlet {

	/**  */
	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(FileUploadServlet.class);


	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("doPost(HttpServletRequest, HttpServletResponse) - start"); //$NON-NLS-1$
		}

		PrintWriter out = response.getWriter();

		try {
		if (ServletFileUpload.isMultipartContent(request)){
			Enumeration param = request.getAttributeNames();

			DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
			diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

			File repositoryPath = new File("/temp");
			diskFileItemFactory.setRepository(repositoryPath);

			ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
			servletFileUpload.setSizeMax(81920); /* the unit is bytes */
			List fileItemsList = servletFileUpload.parseRequest(request);

			Iterator it = fileItemsList.iterator();
			while (it.hasNext()){
			  FileItem fileItem = (FileItem)it.next();
			  if (fileItem.isFormField()){
			    /* The file item contains a simple name-value pair of a form field */
				  System.out.println("Fname : " + fileItem.getFieldName());
			  }
			  else{
			    /* The file item contains an uploaded file */
				  System.out.println("Byte : " + fileItem.get());
			  }
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}

		/*if (!CommonUtil.isImage(CommonUtil.getBytesFromFile(file))) {
			request.getSession().removeAttribute("uploadedfile");
			file.delete();
			response.setContentType("text/xml");
			out.print("<?xml version='1.0' encoding='ISO-8859-1'?>");
			out.print("<msg>value</msg>");
		}*/


		if (logger.isDebugEnabled()) {
			logger.debug("doPost(HttpServletRequest, HttpServletResponse) - ends"); //$NON-NLS-1$
		}
	}
}
